package com.jiang.demo.depotstable;

import com.alibaba.druid.pool.DruidDataSource;
import com.jiang.demo.depotstable.dds.config.DDSConfig;
import com.jiang.demo.depotstable.dds.datasource.DDS;
import com.jiang.demo.depotstable.domain.Store;
import com.jiang.demo.depotstable.store.StoreService;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.List;
import java.util.Map;

@Slf4j
@EnableScheduling
@SpringBootApplication
public class DepotsTableApplication implements CommandLineRunner {

    @Autowired
    StoreService storeService;

    public static void main(String[] args) {
        SpringApplication.run(DepotsTableApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        List<Store> storeList = storeService.getStoreInfos();
        if(storeList.size()<=0){
            log.warn("暂无店铺信息，无法动态添加相应数据源，请先添加");
        }else {
            setProductDDS(storeList);
        }
    }

    // 从数据库中查询店铺信息，然后根据店铺 id 动态创建数据源
    public void setProductDDS(List<Store> storeList) {
        // 根据店铺表创建动态数据源：每个店铺对应一个数据库
        for (Store store:storeList) {
            DruidDataSource productDS = new DruidDataSource();
            productDS.setUrl(DDSConfig.productDBUrl.replace("?port?", store.getPort()+""));
            productDS.setUsername(DDSConfig.productDBUser);
            productDS.setPassword(DDSConfig.productDBPassword);
            productDS.setDriverClassName(DDSConfig.productDBDriverName);
            Map<Object, Object> dsMap = DDS.getInstance().getDataSourceMap();
            dsMap.put("product-db-" + store.getName(), productDS);
            DDS.getInstance().setTargetDataSources(dsMap);
            log.info(store.getName() + " product-db-"+ store.getName() + " 数据源添加完毕");
        }
    }

}
